<template>
  <div class="map-container">
    <div id="map-container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps, watch } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {} from 'element-plus';

const props = defineProps({ 
  showSearch: Boolean,
  wayPoints: {
    type: Array,
    default: () => []
  }
});

// 地图实例
const map = ref(null);
const mapContainer = ref(null);
const placeSearch = ref(null);
const marker = ref(null);
const polylines = ref([]); // 存储折线实例

// 计算当前使用的轨迹数据
const getCurrentFeatures = () => {
  // 只使用接口返回的wayPoints数据
  if (props.wayPoints && props.wayPoints.length > 0) {
    return [{
      strokeWeight: 2,
      strokeColor: '#19A4EB',
      strokeOpacity: 0.8,
      name: '巡逻',
      desc: '飞行轨迹',
      path: props.wayPoints.map(point => ({
        lng: point.longitude || point.lng,
        lat: point.latitude || point.lat,
        Q: point.latitude || point.lat,
        R: point.longitude || point.lng
      })),
      lnglat: {
        lng: props.wayPoints[0].longitude || props.wayPoints[0].lng,
        lat: props.wayPoints[0].latitude || props.wayPoints[0].lat,
        Q: props.wayPoints[0].latitude || props.wayPoints[0].lat,
        R: props.wayPoints[0].longitude || props.wayPoints[0].lng
      },
      type: 'Polyline',
    }];
  }
  // 如果没有数据，返回空数组
  return [];
};

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '4382d57ce20d54c12e3c78ae23f76876',
      version: '2.0',
      plugins: [
        'AMap.PlaceSearch',
        'AMap.Geocoder',
        'AMap.AutoComplete',
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.Marker',
        'AMap.Geolocation',
        'AMap.Polyline',
      ],
    });

    const features = getCurrentFeatures();
    
    // 创建地图实例
    // 如果有轨迹数据，使用第一个点作为中心；否则使用默认中心点
    const defaultCenter = [116.397428, 39.90923]; // 北京天安门
    const center = features[0]?.path?.[0] 
      ? [features[0].path[0].lng, features[0].path[0].lat] 
      : defaultCenter;
    
    map.value = new AMap.Map(mapContainer.value, {
      zoom: features.length > 0 ? 13 : 10,
      center: center,
      viewMode: '2D',
      layers: [new AMap.TileLayer.Satellite()],
    });

    // 添加定位控件
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonPosition: 'RB',
    });
    map.value.addControl(geolocation);
    
    // 绘制所有折线
    if (features.length > 0) {
      drawPolylines(AMap);
    }
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 绘制折线
const drawPolylines = (AMap) => {
  clearPolylines(); // 先清除现有折线

  const features = getCurrentFeatures();

  features.forEach((feature) => {
    if (feature.type === 'Polyline' && feature.path?.length > 0) {
      // 转换坐标格式
      const path = feature.path.map((point) => [point.lng, point.lat]);

      // 创建折线
      const polyline = new AMap.Polyline({
        path: path,
        strokeColor: feature.strokeColor || '#00d68f',
        strokeWeight: feature.strokeWeight || 2,
        strokeOpacity: feature.strokeOpacity || 0.8,
        isOutline: true,
        outlineColor: '',
        lineJoin: 'round',
        lineCap: 'round',
      });

      // 添加到地图
      polyline.setMap(map.value);
      polylines.value.push(polyline);

      // 添加点击事件
      polyline.on('click', () => {
        console.log('点击折线:', feature.name);
      });
    }
  });

  // 自动调整视野以显示所有折线
  if (features.length > 0) {
    map.value.setFitView();
  }
};
// 清除所有折线
const clearPolylines = () => {
  if (polylines.value.length > 0) {
    polylines.value.forEach((polyline) => {
      polyline.setMap(null);
    });
    polylines.value = [];
  }
};
// 生命周期
onMounted(() => {
  initMap();
});

// 监听wayPoints变化，重新绘制轨迹
watch(() => props.wayPoints, (newWayPoints) => {
  if (map.value && newWayPoints && newWayPoints.length > 0) {
    // 延迟一点执行，确保地图已初始化
    setTimeout(() => {
      const AMap = window.AMap;
      if (AMap) {
        drawPolylines(AMap);
      }
    }, 300);
  }
}, { deep: true });

onBeforeUnmount(() => {
  clearPolylines();
  // 清理地图
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 400px;
}

#map-container {
  width: 100%;
  height: 100%;
}

.map-header {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.search-input {
  box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
}

.search-results {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 999;
  width: 400px;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.result-address {
  font-size: 12px;
  color: #666;
}

.result-distance {
  margin-top: 5px;
  font-size: 12px;
  color: #409eff;
}
</style>
